class ZSwitch extends HTMLElement {
	constructor() {
		super();
		const shadowRoot = this.attachShadow({ mode: 'open' });

    this.labelOpen = this.getAttribute("label-open") || "";
		this.labelClose = this.getAttribute("label-close") || "";
		this.valueOpen = this.getAttribute("value-open") || true;
		this.valueClose = this.getAttribute("value-close") || false;
		this.value = this.getAttribute("value") || this.valueOpen

		shadowRoot.innerHTML = this.template();
    // 创建样式
    const style = document.createElement('style');
    style.textContent = this.defineStyle();

    // 将样式添加至shadow 根节点
    shadowRoot.appendChild(style);
	}

	template() {
		return `
      <span class="z-switch-box">
				<span class="z-switch-text open-text">${this.labelOpen}</span>
				<span class="z-switch-text close-text">${this.labelClose}</span>
      </span>
		`;
	}

  defineStyle() {
    return `
			.z-switch-box{
				width: 40px;
				height: 20px;
				background-color: #13ce66;
				border-color: #13ce66;
				border-radius: 10px;
				box-sizing: border-box;
				position: relative;
				display: inline-block;
				cursor: pointer;
				vertical-align: middle;
				transition: border-color .3s,background-color .3s;
			}
			.z-switch-box:after{
				content: "";
				width: 16px;
				height: 16px;
				background: #FFFFFF;
				border-radius: 8px;
				position: absolute;
				transition: all .3s;
				right: 2px;
				top: 2px;
			}
			.z-switch-text{
				font-size: 13px;
				color: #FFFFFF;
			}
			.open-text{
				position: absolute;
				left: 6px;
				top: 1px;
			}
			.close-text{
				position: absolute;
				left: 22px;
				top: 1px;
				display: none;
			}
    `;
  }

  static get observedAttributes() {
    return ['labelOpen', 'labelClose']; 
  }

	// 生命周期：首次被插入文档DOM时
	connectedCallback() {
		if(!JSON.parse($(this).val())) {
			$(this).find('.close-text').css('display','inline-block')
			$(this).find('.open-text').css('display','none')
			$(this).find('.z-switch-box').css('background-color','#dddddc')
			$(this).find('.z-switch-box').css('border-color','#dddddc')
			console.log(this.innerHTML)
		}
	}
	// 生命周期：从文档DOM中删除时
	disconnectedCallback() {
	}
	// 生命周期：被移动到新的文档时
	adoptedCallback() {
	}
	// 生命周期：监听属性变化
	attributeChangedCallback() {
	}
}
customElements.define('z-switch', ZSwitch);
